﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;

namespace Central
{
    public partial class MainWindow
    {
        private readonly DataHandler _dh;

        public MainWindow()
        {
            InitializeComponent();

            _dh = new DataHandler();

            //_pumpStations.Add(new PumpStation("Nørvangen", "127.0.0.1", 9000));

            UpdateList();
        }

        private void ButtonOpret_Click(object sender, RoutedEventArgs e)
        {
            new OpretPumpstation(_dh) {Owner = this}.ShowDialog();
            UpdateList();
        }

        private void UpdateList()
        {
            var stations = ListPumpStations.ItemsSource as List<PumpStation>;
            if (stations != null)
            {
                stations.ForEach(station => station.Stop());
            }
            ListPumpStations.ItemsSource = _dh.GetPumpStations();
        }

        private void ListPumpStations_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (ListPumpStations.SelectedItem != null)
            {
                var station = (PumpStation) ListPumpStations.SelectedItem;
                new PumpStationWindow(station, this, station.Proxy).Show();
                Hide();
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            foreach (PumpStation station in ListPumpStations.Items)
            {
                station.Stop();
            }
            _dh.Close();
        }

        private void ListPumpStations_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete && ListPumpStations.SelectedItem != null)
            {
                var station = (PumpStation) ListPumpStations.SelectedItem;
                _dh.DeletePumpStation(station);
                UpdateList();
            }
        }
    }
}
